package us.icitap.cm.ui.policecase;

import java.util.List;

import us.icitap.cm.CaseManagementUI;
import us.icitap.cm.business.AppListTypeEnum;
import us.icitap.cm.business.entities.AppEntity;
import us.icitap.cm.business.entities.AppList;
import us.icitap.cm.business.entities.Document;
import us.icitap.cm.business.entities.EntityTypeEnum;
import us.icitap.cm.business.entities.Evidence;
import us.icitap.cm.business.entities.Evidence.EvidenceTypeEnum;
import us.icitap.cm.business.entities.regmin.States;
import us.icitap.cm.listeners.AppEntityListener;
import us.icitap.cm.ui.custom.CustBeanFieldGroup;
import us.icitap.cm.ui.custom.CustComboBox;
import us.icitap.cm.ui.custom.CustDateField;
import us.icitap.cm.ui.custom.CustTextArea;
import us.icitap.cm.ui.custom.CustTextField;
import us.icitap.cm.ui.custom.CustomFormLayout;
import us.icitap.cm.ui.shared.AppEntityLayout;
import us.icitap.cm.utils.ProjectLists;
import us.icitap.utils.Result;

import com.vaadin.data.Property.ValueChangeEvent;
import com.vaadin.data.Property.ValueChangeListener;
import com.vaadin.data.util.BeanItemContainer;
import com.vaadin.ui.AbstractSelect.ItemCaptionMode;
import com.vaadin.ui.Button.ClickEvent;
import com.vaadin.ui.Button.ClickListener;
import com.vaadin.ui.CheckBox;
import com.vaadin.ui.FormLayout;
import com.vaadin.ui.TabSheet;
import com.vaadin.ui.VerticalLayout;

public class DocumentDataLayout extends AppEntityLayout {

	/**
	 * 
	 */
	private static final long serialVersionUID = -4809558251925574210L;
	
	private Document document;
	private final CustBeanFieldGroup<Document> binder = new CustBeanFieldGroup<Document>(Document.class);
	
	private final CustComboBox docClassificationSelect = new CustComboBox("Klasifikimi i dokumentit");
	private final CustComboBox docTypeSelect = new CustComboBox("Lloji i dokumentit");
	private final CustTextField documentNoTextField = new CustTextField("Numri i dokumentit");
	private final CustComboBox stateSelect = new CustComboBox("Shteti i leshimit");
	private final CustDateField dateIssuedField = new CustDateField("Data e leshimit");
	private final CustDateField expDateField = new CustDateField("Data e skadimit");
	private final CheckBox isSequenceDocCheckBox = new CheckBox("Dokumenta ne sekuence/seri");
	private final CustTextField startSequenceTextField = new CustTextField("Fillimi i sekuences");
	private final CustTextField endSequenceTextField = new CustTextField("Fundi i sekuences");
	private final CustTextField docTotalNumberTextField = new CustTextField("Numri total i dokumenteve");
	
	private final CustTextArea notesTextArea = new CustTextArea("Shenime");
	
	private final CheckBox evidenceCheckBox = new CheckBox("Eshte prove materiale");
	
	
	protected AppEntityListener listener;
	
	final CustomFormLayout cfl = new CustomFormLayout("450px", "Dokumenta te perfshire ne ngjarje", "Reset", "Ruaj");
	
	boolean editableVisible = false;
	boolean readOnlyVisible = false;

	private final EvidenceEmbeddableDataLayout evidenceEmbDataLayout = new EvidenceEmbeddableDataLayout();
	
	final TabSheet tabSheet = new TabSheet();
	
	public DocumentDataLayout() {
		this.setMargin(true);

		FormLayout fl = new FormLayout();
		fl.addStyleName("cmLayout");
		fl.setMargin(true);
		
		fl.addComponent(this.docClassificationSelect);
		fl.addComponent(this.docTypeSelect);
		fl.addComponent(this.documentNoTextField);
		fl.addComponent(this.stateSelect);
		fl.addComponent(this.dateIssuedField);
		fl.addComponent(this.expDateField);
		fl.addComponent(this.isSequenceDocCheckBox);
		fl.addComponent(this.startSequenceTextField);
		fl.addComponent(this.endSequenceTextField);
		fl.addComponent(this.docTotalNumberTextField);
		fl.addComponent(this.notesTextArea);
		fl.addComponent(this.evidenceCheckBox);
		tabSheet.addTab(fl, "Te dhenat");

		cfl.addComponent(tabSheet);
		cfl.addFooter();
		
		docClassificationSelect.setContainerDataSource(new BeanItemContainer<AppList>(AppList.class, ProjectLists.getList(AppListTypeEnum.DocumentClassification, false)));
		docClassificationSelect.setItemCaptionMode(ItemCaptionMode.EXPLICIT);
		docClassificationSelect.setItemCaptionPropertyId("tag");
		
		stateSelect.setContainerDataSource(new BeanItemContainer<States>(States.class, ProjectLists.getStatesList(false)));
		stateSelect.setItemCaptionMode(ItemCaptionMode.EXPLICIT);
		stateSelect.setItemCaptionPropertyId("tag");
		
		docClassificationSelect.setImmediate(true);
		
		docClassificationSelect.addValueChangeListener(new ValueChangeListener() {
			
			@Override
			public void valueChange(ValueChangeEvent event) {
				docTypeSelect.removeAllItems();
				if(docClassificationSelect.getValue() != null){
					AppList parent = (AppList) docClassificationSelect.getValue();
					Result<List<AppList>> result = CaseManagementUI.appStatelessBean.getPersistenceBean().getAppListChildren(parent);
					if(result.isSucceeded() && result.getObject() != null && !result.getObject().isEmpty()){
						docTypeSelect.setContainerDataSource(new BeanItemContainer<AppList>(AppList.class, result.getObject()));
					}
				}
			}
		});
		
		
		
		
		cfl.addRightClickListener(new ClickListener() {
			
			

			@Override
			public void buttonClick(ClickEvent event) {
				try {
					binder.commit();
					
					if(DocumentDataLayout.this.listener != null){
						if(oldAppEntity == null){
							// Eshte entitet i ri
							if((evidenceCheckBox.getValue().booleanValue())){
								document.getAppEntity().setEvidence(evidenceEmbDataLayout.getEvidence());	
							}
							DocumentDataLayout.this.listener.addAppEntityToReport(document.getAppEntity());
						}
						else{
							//Eshte entitet ekzistues
							System.out.println("Eshte entitet ekzistues");
							document.getAppEntity().setEvidence(evidenceEmbDataLayout.getEvidence());
							if(!oldAppEntity.getDocument().myEquals(document)){
								System.out.println("Entiteti ka ndryshuar");
								if(document.getAppEntity().getEvidence() != null && 
										document.getAppEntity().getEvidence().myEquals(oldAppEntity.getEvidence())){
									System.out.println("Nuk ka ndryshuar prova");
									document.getAppEntity().setEvidence(oldAppEntity.getEvidence());
								}
								
								document.getAppEntity().setRecordUser(CaseManagementUI.getUser().getUsername());
								DocumentDataLayout.this.listener.updateAppEntityIntoReport(oldAppEntity, document.getAppEntity());
							}
							else{
								System.out.println("Entiteti nuk k ndryshuar, as prova");
//								oldAppEntity.replaceEntityReportAssociationList(document.getAppEntity().getReportAssociationList());

								DocumentDataLayout.this.listener.refresh(oldAppEntity);
							}
						
							addAppEntity();
						}
						
					}
						
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		});

		binder.bind(docClassificationSelect, "docClassfication");
		binder.bind(docTypeSelect, "documentType");
		binder.bind(documentNoTextField, "documentNo");
		binder.bind(stateSelect, "states");
		binder.bind(dateIssuedField, "dateIssued");
		binder.bind(expDateField, "expDate");
		binder.bind(isSequenceDocCheckBox, "sequenceDoc");
		binder.bind(startSequenceTextField, "startSequence");
		binder.bind(endSequenceTextField, "endSequence");
		binder.bind(docTotalNumberTextField, "docTotalNo");
		binder.bind(notesTextArea, "notes");
		
		isSequenceDoc(false);
		this.isSequenceDocCheckBox.setImmediate(true);
		this.isSequenceDocCheckBox.addValueChangeListener(new ValueChangeListener() {
			
			@Override
			public void valueChange(ValueChangeEvent event) {
				
				DocumentDataLayout.this.isSequenceDoc(isSequenceDocCheckBox.getValue().booleanValue());
				
				
			}
		});
		
		
		
		evidenceCheckBox.setImmediate(true);
		evidenceCheckBox.addValueChangeListener(new ValueChangeListener() {
			
			@Override
			public void valueChange(ValueChangeEvent event) {
				if(evidenceCheckBox.getValue().booleanValue()){
					// Entiti shoqerohet me prove
					tabSheet.addTab(evidenceEmbDataLayout, "Prove materiale");
					
					if(oldAppEntity != null && oldAppEntity.getEvidence() != null){
						// Entiteti ekzistues ka prove ekzistuese te lidhur me te
						document.getAppEntity().setEvidence(new Evidence(oldAppEntity.getEvidence()));
						evidenceEmbDataLayout.loadEvidence(document.getAppEntity().getEvidence(),true);
					}
					else{
						// Entiteti ekzistues nuk ka prove ekzistues te lidhur me te
						// Krijohet prove e re 
						evidenceEmbDataLayout.createEvidence(EvidenceTypeEnum.MATERIAL);
					}
				}
				else{
					// Entiteti nuk ka prove ekzistuese te lidhur me te
					document.getAppEntity().setEvidence(null);
					tabSheet.removeComponent(evidenceEmbDataLayout);
				}	
			}
		});
		
		
	}
	
	private  void isSequenceDoc(boolean value){
		this.startSequenceTextField.setVisible(value);
		this.endSequenceTextField.setVisible(value);
		this.docTotalNumberTextField.setVisible(value);
		if(!value){
			this.startSequenceTextField.setValue(null);
			this.endSequenceTextField.setValue(null);
			this.docTotalNumberTextField.setValue(null);
		}
	}

	public void showEditableForm(){
		if(editableVisible) return ;
		
		this.removeAllComponents();
		this.addComponent(cfl);
		
		editableVisible = true;
		readOnlyVisible = false;
	}
	

	public void showReadOnlyForm(){
		if(readOnlyVisible) return;
		this.removeAllComponents();
		VerticalLayout vl = ViewCaseLayout.showDocument(document);
		vl.setCaption(EntityTypeEnum.DOCUMENT.getCaption());
		this.addComponent(vl);
		editableVisible = false;
		readOnlyVisible = true;
	}
	
	
	@Override
	public void addAppEntity() {
		this.tabSheet.setSelectedTab(0);
		AppEntity appEntity = new AppEntity(CaseManagementUI.getUser().getUsername(), EntityTypeEnum.DOCUMENT);
		document = appEntity.getDocument();
		
		binder.setItemDataSource(document);
		this.showEditableForm();
	}

	private AppEntity oldAppEntity;
	
	@Override
	public void loadAppEntity(AppEntity appEntity, boolean editable) {


		oldAppEntity = appEntity;
		
		AppEntity newAppEntity = new AppEntity(appEntity);
		
		this.document = newAppEntity.getDocument();
		binder.setItemDataSource(document);
		
		if(newAppEntity.getEvidence()!= null){
			evidenceCheckBox.setValue(new Boolean(true));
			evidenceEmbDataLayout.loadEvidence(newAppEntity.getEvidence(), true);
			tabSheet.addTab(evidenceEmbDataLayout, "Prove materiale");
		}
		else{
			evidenceCheckBox.setValue(new Boolean(false));
		}
			
		
		
		if(editable) 
			this.showEditableForm();
		
		else
			this.showReadOnlyForm();
	}

	@Override
	public void addAppEntityListener(AppEntityListener listener) {
		this.listener = listener;
		
	}
	

}
